package com.gnerv.sylvanas.module.sse.event.listener;

import com.gnerv.sylvanas.framework.common.model.sse.SseResult;
import com.gnerv.sylvanas.framework.core.event.SseMessagePushEvent;
import com.gnerv.sylvanas.module.sse.operation.SseOperationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;


/**
 * 监听sse消息推送事件
 *
 * @author Gnerv LiGen
 */
@Slf4j
@Component
@AllArgsConstructor
public class SseMessagePushEventListener implements ApplicationListener<SseMessagePushEvent> {

    private final SseOperationService sseOperationService;

    @Async(value = "ssePushExecutor")
    @Override
    public void onApplicationEvent(SseMessagePushEvent sseMessagePushEvent) {
        String clientId = sseMessagePushEvent.getClientId();
        SseResult<?> sseResult = sseMessagePushEvent.getSseResult();
        if (clientId == null) {
            List<SseEmitter> sseEmitters = sseOperationService.selectListSseEmitterByTopic(sseResult.getTopic());
            for (SseEmitter sseEmitter : sseEmitters) {
                sseOperationService.pushText(sseEmitter, sseResult);
            }
        } else {
            SseEmitter sseEmitter = sseOperationService.selectSseEmitterByClientIdAndTopic(clientId, sseResult.getTopic());
            sseOperationService.pushText(sseEmitter, sseResult);
        }
    }
}
